/*
 * Copyright (c) 2000-2019 TeamDev Ltd. All rights reserved.
 * TeamDev PROPRIETARY and CONFIDENTIAL.
 * Use is subject to license terms.
 */
package samples;

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserType;
import com.teamdev.jxbrowser.chromium.Callback;
import com.teamdev.jxbrowser.chromium.FocusListener;
import com.teamdev.jxbrowser.chromium.PopupContainer;
import com.teamdev.jxbrowser.chromium.PopupHandler;
import com.teamdev.jxbrowser.chromium.PopupParams;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import java.awt.BorderLayout;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

/**
 * The sample demonstrates how to receive a request to focus the popup window from JavaScript.
 */
public class FocusSample {

    public static void main(String[] args) {

        final Browser browser = new Browser(BrowserType.LIGHTWEIGHT);
        BrowserView view = new BrowserView(browser);
        JFrame frame = new JFrame("JxBrowser - Focus test (Swing)");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(view, BorderLayout.CENTER);
        frame.setSize(800, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.setPopupHandler(new MyPopupHandler());

        Browser.invokeAndWaitFinishLoadingMainFrame(browser, new Callback<Browser>() {
            @Override
            public void invoke(Browser browser) {
                browser.loadHTML("<button onclick=\"popup.focus();\">Focus</button>");
            }
        });
        browser.executeJavaScript("var popup = window.open('https://google.com')");
    }

    private static class MyPopupHandler implements PopupHandler {
        @Override
        public PopupContainer handlePopup(PopupParams params) {
            return new PopupContainer() {
                public void insertBrowser(final Browser browser, final Rectangle initialBounds) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            BrowserView browserView = new BrowserView(browser);
                            final JFrame frame = new JFrame();
                            frame.setLocationByPlatform(true);
                            frame.setSize(800, 600);
                            frame.add(browserView, BorderLayout.CENTER);
                            browser.addFocusListener(new FocusListener() {
                                @Override
                                public void onFocusRequested() {
                                    frame.requestFocus();
                                }
                            });
                            frame.setVisible(true);
                        }
                    });
                }
            };
        }
    }
}
